#!/bin/bash
# Author: wanglx <15201376500@163.com>
#
# Date: 2024/05/07
#
# auto create base raid1 for linux os

auto_mkpart_disk(){
_cu_dev=$1

# 初始化磁盘分区表
parted ${_cu_dev} mklabel gpt

# 创建第一个sda1分区 500MB ，用于EFI启动
parted -a optimal ${_cu_dev} mkpart ESP fat32 0% 500MB
parted ${_cu_dev} set 1 esp on

parted -a optimal ${_cu_dev} mkpart primary ext4 500MB 100%
parted ${_cu_dev} name 2 RAID

# 完成后检查
parted ${_cu_dev} print

# 分区格式化
mkfs.vfat -F 32 -n efi-boot ${_cu_dev}1

}

auto_mkpart_md(){
_cu_dev=$1
_swap_size=$2

parted ${_cu_dev} mklabel gpt
## mkpart part-type name fs-type start end

parted -a optimal ${_cu_dev} mkpart primary linux-swap 1MB ${_swap_size}

parted -a optimal ${_cu_dev} mkpart primary ext4 ${_swap_size} 100%
parted ${_cu_dev} name 2 root

parted ${_cu_dev} print

mkfs.ext4 -F -L 'root' ${_cu_dev}p2
mkswap  ${_cu_dev}p1
}

# do mkpart

auto_mkpart_disk  /dev/sda

auto_mkpart_disk  /dev/sdb

mdadm -E /dev/sd[a-b]

mdadm -E /dev/sd[a-b]2

# create soft raid1
mdadm --create --verbose /dev/md0 --level=1 --raid-devices=2 /dev/sd[a-b]2
wait
cat /proc/mdstat

mdadm -E /dev/sd[a-b]2
sleep 3
MD_NAME=$(cat /proc/mdstat |grep -E "sda|sdb" |awk '/raid1/ {print $1}'|uniq)

mdadm --detail /dev/$MD_NAME

[ -b /dev/$MD_NAME ]&& auto_mkpart_md /dev/$MD_NAME  2GB
